﻿namespace Contoso.ActiveDirectory {

    #region Usings
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.DirectoryServices.ActiveDirectory;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    #endregion

    public class SiteMethods {

        /// <summary>
        /// Creates a SiteLinkBridge for the specified SiteLinks. A SiteLinkBridge requires a minimum of two SiteLinks.
        /// </summary>
        /// <param name="forestDnsName">The forest DNS name</param>
        /// <param name="siteLink1Name">The first SiteLink name</param>
        /// <param name="siteLink2Name">The second SiteLink name</param>
        public void CreateSiteLinkBridge(string forestDnsName, string siteLinkBridgeName, string siteLink1Name, string siteLink2Name) {
            Debug.WriteLine(string.Format("{0}  [ThreadID: {1}]  {2} forestDnsName: {3} siteLinkBridgeName: {4} siteLink1Name: {5} siteLink2Name: {6}", 
                DateTime.Now.TimeOfDay, Thread.CurrentThread.ManagedThreadId, CustomExtensions.CurrentMethodName(),
                forestDnsName ?? "NULL", siteLinkBridgeName ?? "NULL", siteLink1Name ?? "NULL", siteLink2Name ?? "NULL"));

            #region Validation
            if (string.IsNullOrWhiteSpace(forestDnsName)) {
                throw new ArgumentNullException("forestDnsName");
            }
            if (string.IsNullOrWhiteSpace(siteLinkBridgeName)) {
                throw new ArgumentNullException("siteLinkBridgeName");
            }
            if (string.IsNullOrWhiteSpace(siteLink1Name)) {
                throw new ArgumentNullException("siteLink1Name");
            }
            if (string.IsNullOrWhiteSpace(siteLink2Name)) {
                throw new ArgumentNullException("siteLink2Name");
            } 
            #endregion

            var forestContext = new DirectoryContext(DirectoryContextType.Forest, forestDnsName);
            var adTransport = ActiveDirectoryTransportType.Rpc;

            var siteLinkBridge = new ActiveDirectorySiteLinkBridge(forestContext, siteLinkBridgeName, adTransport);

            var siteLink1 = ActiveDirectorySiteLink.FindByName(forestContext, siteLink1Name);
            if (siteLink1 == null) {
                throw new ApplicationException(string.Format("SiteLink: {0} not found.", siteLink1Name));
            }

            var siteLink2 = ActiveDirectorySiteLink.FindByName(forestContext, siteLink2Name);
            if (siteLink2 == null) {
                throw new ApplicationException(string.Format("SiteLink: {0} not found.", siteLink2Name));
            }

            siteLinkBridge.SiteLinks.Add(siteLink1);
            siteLinkBridge.SiteLinks.Add(siteLink2);
            siteLinkBridge.Save();

        }
    }
}
